#include <cstdio>
#include <tsubamegaeshi2d/socket.h>
#include <tsubamegaeshi2d/message_loop.h>

class stdin_listener :public tsubamegaeshi::MessageLoop::FDListener {
  FILE* fp_;
  tsubamegaeshi::Socket& socket_;

public:
  stdin_listener(FILE* fp, tsubamegaeshi::Socket& socket)
    :fp_(fp),socket_(socket)
  {}

  bool listen(int fd) {
    char buf[MAXMESG + 1];

    fgets(buf, MAXMESG, fp_) ;
    if (socket_.send(buf) == -1)
      return false;
    return true;
  }
};

class socket_listener :public tsubamegaeshi::MessageLoop::FDListener {
  tsubamegaeshi::Socket& socket_;

public:
  socket_listener(tsubamegaeshi::Socket& socket)
    :socket_(socket)
  {}

  bool listen(int fd) {
    char buf[MAXMESG];

    int n = socket_.receive(buf, MAXMESG) ;
    if(n == -1)
      return false ;
    else if(n > 0){
      puts(buf) ;
    }
    return true;
  }
};

int main(int argc, char **argv)
{
  tsubamegaeshi::Socket sock ;
  char *server ;
  int port ;

  if(argc == 3) {
    server = argv[1] ;
    port = atoi(argv[2]) ;
  } else if (argc == 2) {
    server = argv[1] ;
    port = 6000 ;
  } else {
    server = "localhost" ;
    port = 6000 ;
  }

  if (!sock.init(server, port)) {
    exit(1) ;
  }

  tsubamegaeshi::MessageLoop::get_instance()->add_fd_listener(fileno(stdin), new stdin_listener(stdin, sock));
  tsubamegaeshi::MessageLoop::get_instance()->add_fd_listener(sock.fd(), new socket_listener(sock));
  tsubamegaeshi::MessageLoop::get_instance()->run();

  sock.close() ;
}


